package com.mango.lucene.demo.controller;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.mango.lucene.demo.util.LuceneUtil;

@ControllerBind(controllerKey = "/")
public class IndexController extends Controller{
	
	public void index() {
		//更新索引
		try {
			LuceneUtil.updateIndex();
		} catch (IOException e) {
			e.printStackTrace();
		}
		render("index.html");
	}
	
	public void search(){
		String keyword = this.getPara("keyword");
		List<Map<String,String>> data = Lists.newArrayList();
		Analyzer analyzer = new IKAnalyzer();
		Directory directory;
		try {
			directory = FSDirectory.open(new File("tmp/testindex"));
			// 设定搜索目录
			DirectoryReader ireader = DirectoryReader.open(directory);
			IndexSearcher isearcher = new IndexSearcher(ireader);
			// Parse asimple query that searches for "text":
			// QueryParserparser = new QueryParser(Version.LUCENE_CURRENT,
			// "fieldname",analyzer);
			// 使用同样的方式对多field进行搜索
			String[] multiFields = { "title", "content" };
			
			MultiFieldQueryParser parser = new MultiFieldQueryParser(
					Version.LUCENE_4_9, multiFields, analyzer);
			// 设定具体的搜索词
			Query query = parser.parse(keyword);
			
			TopDocs docs =isearcher.search(query,null,1000);//查找
			ScoreDoc[] hits = docs.scoreDocs;
			
			SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
			Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
			 //高亮htmlFormatter对象  
	        //设置高亮附近的字数  
	        highlighter.setTextFragmenter(new SimpleFragmenter(100));  
			// assertEquals(1, hits.length);
			System.out.println("Searched " + hits.length + " documents.");
			// Iteratethrough the results:
			for (int i = 0; i < hits.length; i++) {
				Document hitDoc = isearcher.doc(hits[i].doc);
				String[] scoreExplain = null;
				// scoreExplain可以显示文档的得分详情，这里用split截取总分
				scoreExplain = isearcher.explain(query, hits[i].doc).toString()
						.split(" ", 2);
				String scores = scoreExplain[0];
				// assertEquals("Thisis the text to be indexed.",
				// hitDoc.get("fieldname"));
				System.out.println("score:"+scores);
				String title =hitDoc.get("title");
				String content = hitDoc.get("content");
				String id = hitDoc.get("id");
				String redTitle = title;
				//过滤掉分词单个字的
				if(content!=null){
					if(!title.contains(keyword) && !content.contains(keyword)){
						break;
					}
				}else{
					if(!title.contains(keyword)){
						break;
					}
				}
				if(title.contains(keyword)){
					redTitle = highlighter.getBestFragment(analyzer.tokenStream(title, new StringReader(title)), title); 
				}
	            String redContent = "";
	            if(content!=null && content.contains(keyword)){
	            	content = delHTMLTag(content);//去掉html标签
	            	redContent = highlighter.getBestFragment(analyzer.tokenStream(content, new StringReader(content)), content);   
	            }
	            Map<String,String> obj = Maps.newHashMap();
				obj.put("id", id);
				obj.put("title", redTitle);
				obj.put("content", redContent);
				data.add(obj);
			}
			ireader.close();
			directory.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.setAttr("datalist", data);
		this.setAttr("len", data.size());
		this.setAttr("keyword", keyword);
		render("index.html");
	}
	
	public static String delHTMLTag(String htmlStr){ 
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
         
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
        Matcher m_script=p_script.matcher(htmlStr); 
        htmlStr=m_script.replaceAll(""); //过滤script标签 
         
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
        Matcher m_style=p_style.matcher(htmlStr); 
        htmlStr=m_style.replaceAll(""); //过滤style标签 
         
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //过滤html标签 

        return htmlStr.trim(); //返回文本字符串 
    } 
}
